package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.EasyUITable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Service
public class ItemServiceImpl implements ItemService {
	
	@Autowired
	private ItemMapper itemMapper;

	@Autowired
	private ItemDescMapper itemDescMapper;

	public EasyUITable findItemByPage(int page, int rows) {
		IPage<Item> iPage = new Page<>(page,rows);
		QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
		queryWrapper.orderByDesc("updated");
		iPage = itemMapper.selectPage(iPage, queryWrapper);
		return new EasyUITable(iPage.getTotal(), iPage.getRecords());
	}

	@Override
	public void saveItem(Item item) {
		item.setStatus(1);	//默认是正常状态
		//.setCreated(new Date())
		//.setUpdated(item.getCreated());
		itemMapper.insert(item);
	}


	//一般更新操作都是根据主键更新
	//Sql: update tb_item set titel=#{xxxx},xx,x,x,x,x, where id=#{xxx}
	@Override
	public void updateItem(Item item) {
		//根据对象中不为null的元素充当set条件
		itemMapper.updateById(item);
	}

	//批量删除操作
	@Override
	public void deleteItems(Long[] ids) {
		//List<Long> longList = Arrays.asList(ids);
		//itemMapper.deleteBatchIds(longList);

		//手动的删除数据
		itemMapper.deleteItems(ids);

	}

	//作业:sql手动完成
	//参数说明:  entity:修改数据的值   updateWrapper
	@Override
	public void updateStatus(Long[] ids, Integer status) {
		Item item = new Item();
		item.setStatus(status);
		//where id in (1,2,3,4)
		UpdateWrapper<Item> updateWrapper = new UpdateWrapper<>();
		updateWrapper.in("id", Arrays.asList(ids));
		itemMapper.update(item,updateWrapper);
	}

	/*@Override
	public EasyUITable findItemByPage(int page, int rows) {

		long total = itemMapper.selectCount(null);
		int startNum = (page-1)*rows;
		List<Item> itemList = itemMapper.findItemByPage(startNum,rows);
		return new EasyUITable(total,itemList);
	}*/

	@Override
	public ItemDesc findItemDescById(Long itemId) {

		return itemDescMapper.selectById(itemId);
	}


}
